package com.inei.cie.utilitarios;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import android.app.Activity;
import android.app.Dialog;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.view.Window;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.inei.cie.R;
import com.inei.cie.capitulov.CapituloV_Pisos;
import com.inei.cie.capitulov.CapituloV_Total_Ambientes_Activity;
import com.inei.cie.dao.CapituloVDao;
import com.inei.cie.entidades.P5;
import com.inei.cie.entidades.P5_F;

public class ListadoPisosAdapter extends BaseAdapter {
	Context context;
	public ArrayList<Integer> listaPisos;
	private int cantidadPisos;
	private Bitmap imagen = null;
	private String codLocal;
	private int numeroPredio;
	public Boolean foto_tomada = false;
	private static final int TAKE_PHOTO_CODE = 1;
	private Activity activity;
	public static List<String> fotosPisos;
	// public static List<String> escala;
	private CapituloVDao cap5Dao;
	private List<P5_F> p5_f;
	public Bundle b;
	private int primera_vez = 0;

	public ListadoPisosAdapter(Context context, int cantidadPisos,
			Activity activity, String codLocal, int numeroPredio, Bundle b) {
		cap5Dao = new CapituloVDao(context);
		this.codLocal = codLocal;
		this.numeroPredio = numeroPredio;
		this.activity = activity;
		this.context = context;
		listaPisos = new ArrayList<Integer>();
		this.cantidadPisos = cantidadPisos;
		this.b = b;
		fotosPisos = new ArrayList<String>(this.cantidadPisos - 1);
		// escala = new ArrayList<String>(this.cantidadPisos - 1);
		p5_f = cap5Dao.obtenerP5_FLocal(this.codLocal, this.numeroPredio);
		for (int i = 0; i < this.cantidadPisos; i++) {
			listaPisos.add((i + 1));
			fotosPisos.add("");
			// escala.add("");
		}
	}

	@Override
	public int getCount() {
		return listaPisos.size();
	}

	@Override
	public Object getItem(int pos) {
		return listaPisos.get(pos);
	}

	@Override
	public long getItemId(int arg0) {
		// TODO Auto-generated method stub
		return 0;
	}

	@Override
	public View getView(final int pos, View view, ViewGroup grupo) {
		View item = view;
		final ViewHolder holder;
		if (item == null) {
			LayoutInflater inflater = (LayoutInflater) context
					.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
			item = inflater.inflate(R.layout.item_lista_pisos, null);
			holder = new ViewHolder();
			holder.tvItem = (TextView) item.findViewById(R.id.tvItem);
			// holder.eteEscalaInicial = (EditText)
			// item.findViewById(R.id.eteEscalaInicial);
			// holder.eteEscalaFinal = (EditText)
			// item.findViewById(R.id.eteEscalaFinal);
			holder.butTomarFoto = (Button) item.findViewById(R.id.butTomarFoto);
			holder.butVerFoto = (Button) item.findViewById(R.id.butVerFoto);
			holder.butIngresarAmbientes = (Button) item
					.findViewById(R.id.butIngresarAmbientes);
			item.setTag(holder);

		} else {
			holder = (ViewHolder) item.getTag();
		}
		holder.tvItem.setText("Piso Nro " + listaPisos.get(pos));
		holder.butTomarFoto.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				takePhoto((pos + 1));
				cap5Dao.actualizarP5Pisos(codLocal, numeroPredio, (pos + 1),
						getTempFile(context, (pos + 1)).getAbsolutePath(), ""
								+ "-" + "", 1, 1, 0);
				/*
				 * if(holder.eteEscalaInicial.getText().length() > 0 &&
				 * holder.eteEscalaFinal.getText().length() > 0){ takePhoto((pos
				 * + 1)); cap5Dao.actualizarP5Pisos(codLocal, numeroPredio, (pos
				 * + 1), getTempFile(context, (pos + 1)).getAbsolutePath(),
				 * holder.eteEscalaInicial.getText().toString() + "-" +
				 * holder.eteEscalaFinal.getText().toString(), 1, 1, 0); } else{
				 * Toast.makeText(context,
				 * "Debe ingresar la escala de la foto Nro " + (pos + 1),
				 * Toast.LENGTH_SHORT).show(); }
				 */
			}
		});

		holder.butVerFoto.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				LayoutInflater inflater = (LayoutInflater) context
						.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
				imagen = obtenerImagenPiso(codLocal, numeroPredio, (pos + 1));
				final Dialog settingsDialog = new Dialog(context);
				settingsDialog.getWindow().requestFeature(
						Window.FEATURE_NO_TITLE);
				settingsDialog.setContentView(inflater.inflate(
						R.layout.foto_gps, null));
				ImageView iviFoto = (ImageView) settingsDialog
						.findViewById(R.id.iviFotoGPS);
				Button butCancelar = (Button) settingsDialog
						.findViewById(R.id.butCerrar);
				iviFoto.setImageBitmap(imagen);
				settingsDialog.show();
				butCancelar.setOnClickListener(new OnClickListener() {

					@Override
					public void onClick(View v) {
						settingsDialog.dismiss();
					}
				});

			}
		});

		holder.butIngresarAmbientes.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				/*
				 * CapituloVDao cap5Dao = new CapituloVDao(context); P5 obj2 =
				 * cap5Dao.obtenerP5Local(codLocal, numeroPredio);
				 * 
				 * String g = b.getString("grabado_correcto"); if(g == null){
				 * holder.butIngresarAmbientes.setTag(1); }else{
				 * if(g.equals("Piso " + pos + 1)){
				 * holder.butIngresarAmbientes.setTag(2); } else{
				 * holder.butIngresarAmbientes.setTag(1); } } primera_vez =
				 * Integer
				 * .parseInt(String.valueOf(holder.butIngresarAmbientes.getTag
				 * ()));
				 */
				// holder.butIngresarAmbientes.setTag(1);
				Intent ambientes = new Intent(activity,
						CapituloV_Total_Ambientes_Activity.class);
				b.putInt("P5_NroPred", numeroPredio);
				b.putInt("P5_NroPiso", (pos + 1));
				// b.putInt("primera_vez", primera_vez);
				ambientes.putExtras(b);
				context.startActivity(ambientes);
				
			}
		});

		/*
		 * if(p5_f != null){ p5_f = cap5Dao.obtenerP5_FLocal(this.codLocal,
		 * this.numeroPredio); String[] escala =
		 * p5_f.get(pos).getP5_Escala().split("-"); if(escala.length > 1){
		 * holder.eteEscalaInicial.setText(escala[0]);
		 * holder.eteEscalaFinal.setText(escala[1]); } else{
		 * holder.eteEscalaInicial.setText("");
		 * holder.eteEscalaFinal.setText(""); }
		 * 
		 * }
		 */
		return item;
	}

	class ViewHolder {
		TextView tvItem;
		// EditText eteEscalaInicial;
		// EditText eteEscalaFinal;
		Button butTomarFoto;
		Button butVerFoto;
		Button butIngresarAmbientes;
	}

	public Bitmap obtenerImagenPiso(String codigoLocal, int numeroPredio,
			int piso) {
		Bitmap bitmap = null;
		try {
			File sdCard = Environment.getExternalStorageDirectory();
			File directory = new File(sdCard.getAbsolutePath() + "/CIE2013/"
					+ codigoLocal + "/PRED_" + numeroPredio + "/CAP5");
			File file = new File(directory, codigoLocal + "_" + numeroPredio
					+ "_Piso" + piso + ".png");
			FileInputStream streamIn;
			streamIn = new FileInputStream(file);
			bitmap = BitmapFactory.decodeStream(streamIn);
			streamIn.close();
			foto_tomada = true;
		} catch (FileNotFoundException e) {
			foto_tomada = false;
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			foto_tomada = false;
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return bitmap;
	}

	private void takePhoto(int pos) {
		final Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
		intent.putExtra(MediaStore.EXTRA_OUTPUT,
				Uri.fromFile(getTempFile(this.context, pos)));
		activity.startActivityForResult(intent, TAKE_PHOTO_CODE);
		// activity.finish();
	}

	private File getTempFile(Context context, int pos) {
		File sdCard = Environment.getExternalStorageDirectory();
		File dir = new File(sdCard.getAbsolutePath() + "/CIE2013/" + codLocal
				+ "/PRED_" + numeroPredio + "/CAP5");
		final File path = dir;
		if (!path.exists()) {
			path.mkdirs();
		}
		return new File(path, codLocal + "_" + numeroPredio + "_Piso" + pos
				+ ".png");
	}
}
